<template>
  <!-- 搜索及操作区域 -->
  <x-search>
    <template #search>
      <a-range-picker
        v-model:value="rankDate"
        style="width: 250px; margin-left: 10px"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
      <a-button type="primary" style="margin-left: 10px" @click="fetchRankData">
        查询
      </a-button>
      <a-button style="margin-left: 10px" @click="resetRank"> 重置 </a-button>
    </template>
  </x-search>

  <!-- 四排名分析图 -->
  <div class="rank-charts">
    <!-- 成绩排名 -->
    <!-- <x-card :message="message3" :width="49" :height="height1"> -->
    <x-card message="成绩排名" :width="49" :height="height">
      <div ref="chartRef1" style="width: 100%; height: 300px"></div>
    </x-card>

    <!-- 考勤排名 -->
    <x-card message="考勤排名" :width="49" :height="height">
      <div ref="chartRef2" style="width: 100%; height: 300px"></div>
    </x-card>

    <!-- 内务排名 -->
    <x-card message="内务排名" :width="49" :height="height">
      <div ref="chartRef3" style="width: 100%; height: 300px"></div>
    </x-card>

    <!-- 作业排名 -->
    <x-card message="作业排名" :width="49" :height="height">
      <div ref="chartRef4" style="width: 100%; height: 300px"></div>
    </x-card>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import * as echarts from "echarts";
import XSearch from "./XSearch.vue";
import XCard from "./XCard.vue";
import type { Dayjs } from "dayjs";
import http from "../routerutils/http";

type RankData = {
  top: Array<{ name: string; value: number }>;
  bottom: Array<{ name: string; value: number }>;
};
// 日期范围
const rankDate = ref<[Dayjs, Dayjs]>([null, null]);
// 搜索按钮
const fetchRankData = () => {
  initChart1();
  initChart2();
  initChart3();
  initChart4();
};
// 重置筛选
const resetRank = () => {
  rankDate.value = [null, null];
  initChart1();
  initChart2();
  initChart3();
  initChart4();
};
// 图表引用
const chartRef1 = ref<HTMLElement>();
let chartInstance1: echarts.ECharts | null = null;

const initChart1 = async () => {
  try {
    if (!chartRef1.value) return;

    // 获取数据
    const res = await http.get("/api/analysis/classRank", {
      params: {
        start_time: rankDate.value[0],
        end_time: rankDate.value[1],
      },
    });

    const { topFive, bottomFive } = res.data.results;
    const allScores = [...topFive, ...bottomFive].map((item) => item.score_all);

    // 计算平均分
    const average = Number(
      (
        allScores.reduce((sum, score) => sum + score, 0) / allScores.length
      ).toFixed(2)
    );

    // 处理数据格式
    const topData = topFive.map((item: any, index: number) => ({
      name: item.student_name,
      value: [index, item.score_all, item.date],
      itemStyle: { color: "#409EFF" }, // 蓝色表示优秀
    }));

    const bottomData = bottomFive.map((item: any, index: number) => ({
      name: item.student_name,
      value: [index + topFive.length, item.score_all, item.date], // +1为平均线留位置
      itemStyle: { color: "#E6A23C" }, // 橙色表示待提升
    }));

    // 配置图表
    const option = {
      title: {
        text: "成绩排名分析 (平滑折线图)",
        subtext: `平均分: ${average}分`,
        left: "center",
      },
      tooltip: {
        trigger: "item",
        formatter: (params: any) => {
          const [x, score, date] = params.data.value;
          return `
            <div style="font-weight:bold">${params.data.name}</div>
            <div>日期: ${date}</div>
            <div>分数: <span style="color:${
              params.color
            }">${score}分</span></div>
            <div>排名: ${x < topFive.length ? "Top" : "Bottom"} ${
            x < topFive.length ? x + 1 : x - topFive.length
          }</div>
          `;
        },
      },
      grid: {
        left: "10%",
        right: "10%",
        bottom: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: [
          ...topFive.map((item: any, i: number) => `${item.student_name}`),
          //   '平均分',
          ...bottomFive.map((item: any, i: number) => `${item.student_name}`),
        ],
        axisLabel: {
          rotate: 45,
          interval: 0,
          color: (index: number) =>
            index < topFive.length
              ? "#409EFF"
              : index > topFive.length
              ? "#E6A23C"
              : "#F56C6C",
        },
        axisLine: {
          lineStyle: {
            color: "#ddd",
          },
        },
      },
      yAxis: {
        type: "value",
        name: "分数",
        min: 0,
        max: 100,
        axisLabel: {
          formatter: "{value} 分",
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
          },
        },
      },
      series: [
        {
          name: "成绩排名",
          type: "line",
          smooth: true,
          symbolSize: 8,
          data: [...topData, ...bottomData],
          lineStyle: {
            width: 3,
            shadowColor: "rgba(0, 0, 0, 0.1)",
            shadowBlur: 10,
            shadowOffsetY: 5,
          },
          markLine: {
            // silent: true,
            symbol: "none",
            lineStyle: {
              color: "#409EFF",
              width: 2,
              type: "dashed",
            },
            label: {
              position: "middle",
              formatter: "平均分 {c}",
              color: "#F56C6C",
              fontSize: 12,
            },
            data: [
              {
                yAxis: average,
                name: "平均分",
              },
            ],
          },
        },
      ],
      visualMap: {
        top: 50,
        right: 10,
        pieces: [
          {
            gt: average,
            lte: 100,
            color: "#409EFF",
          },
          {
            gt: 0,
            lte: average,
            color: "#E6A23C",
          },
        ],
        outOfRange: {
          color: "#999",
        },
      },
    };

    // 初始化或更新图表
    if (!chartInstance1) {
      chartInstance1 = echarts.init(chartRef1.value);
    }
    chartInstance1.setOption(option);

    // 窗口自适应
    window.addEventListener("resize", () => chartInstance1?.resize());
  } catch (error) {
    console.error("成绩数据加载失败:", error);
    message.error("成绩排名数据加载失败");
  }
};
// 考勤排名
const chartRef2 = ref<HTMLElement>();
let chartInstance2: echarts.ECharts | null = null;

const initChart2 = async () => {
  try {
    if (!chartRef2.value) return;

    // 获取数据
    const res = await http.get("/api/analysis/attendRank", {
      params: {
        start_time: rankDate.value[0],
        end_time: rankDate.value[1],
      },
    });

    const { topFive, bottomFive } = res.data.results;
    const allScores = [...topFive, ...bottomFive].map((item) => item.score);

    // 计算平均分
    const average = Number(
      (
        allScores.reduce((sum, score) => sum + score, 0) / allScores.length
      ).toFixed(2)
    );

    // 处理数据格式
    const topData = topFive.map((item: any, index: number) => ({
      name: item.student_name,
      value: [index, item.score, item.date],
      itemStyle: { color: "#67C23A" }, // 绿色表示优秀
    }));

    const bottomData = bottomFive.map((item: any, index: number) => ({
      name: item.student_name,
      value: [index + topFive.length, item.score, item.date],
      itemStyle: { color: "#F56C6C" }, // 红色表示待提升
    }));

    // 配置图表
    const option = {
      title: {
        text: "考勤排名分析 (平滑折线图)",
        subtext: `平均分: ${average}分`,
        left: "center",
        textStyle: {
          fontSize: 16,
          fontWeight: "bold",
        },
      },
      tooltip: {
        trigger: "item",
        formatter: (params: any) => {
          const [x, score, date] = params.data.value;
          return `
            <div style="font-weight:bold;margin-bottom:5px">${
              params.data.name
            }</div>
            <div style="margin-bottom:3px">日期: ${date}</div>
            <div style="margin-bottom:3px">考勤分: <span style="color:${
              params.color
            };font-weight:bold">${score}分</span></div>
            <div>排名: ${x < topFive.length ? "Top" : "Bottom"} ${
            x < topFive.length ? x + 1 : x - topFive.length + 1
          }</div>
          `;
        },
        backgroundColor: "rgba(255,255,255,0.9)",
        borderColor: "#ddd",
        borderWidth: 1,
        padding: [10, 15],
      },
      grid: {
        left: "12%",
        right: "12%",
        bottom: "20%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: [
          ...topFive.map((item: any) => item.student_name),
          ...bottomFive.map((item: any) => item.student_name),
        ],
        axisLabel: {
          rotate: 45,
          interval: 0,
          color: (index: number) =>
            index < topFive.length ? "#67C23A" : "#F56C6C",
          fontSize: 12,
        },
        axisLine: {
          lineStyle: {
            color: "#eee",
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        type: "value",
        name: "考勤分",
        nameTextStyle: {
          padding: [0, 0, 0, 40], // 调整名称位置
        },
        min: Math.min(...allScores) - 2,
        max: Math.max(...allScores) + 2,
        axisLabel: {
          formatter: "{value} 分",
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
            // color: "#f0f0f0",
          },
        },
      },
      series: [
        {
          name: "考勤排名",
          type: "line",
          smooth: true,
          symbolSize: 10,
          data: [...topData, ...bottomData],
          lineStyle: {
            width: 3,
            shadowColor: "rgba(0, 0, 0, 0.1)",
            shadowBlur: 8,
            shadowOffsetY: 5,
          },
          markLine: {
            // silent: true,
            symbol: "none",
            lineStyle: {
              color: "#409EFF",
              width: 2,
              type: "dashed",
            },
            label: {
              position: "middle",
              formatter: "平均分 {c}",
              color: "#F56C6C",
              fontSize: 12,
            },
            data: [
              {
                yAxis: average,
                name: "平均分",
              },
            ],
          },
          itemStyle: {
            borderWidth: 2,
            borderColor: "#fff",
          },
        },
      ],
      visualMap: {
        top: 50,
        right: 20,
        pieces: [
          {
            gt: average,
            color: "#67C23A",
          },
          {
            lte: average,
            color: "#F56C6C",
          },
        ],
        textStyle: {
          color: "#666",
        },
      },
    };

    // 初始化或更新图表
    if (!chartInstance2) {
      chartInstance2 = echarts.init(chartRef2.value);
    }
    chartInstance2.setOption(option);

    // 窗口自适应
    window.addEventListener("resize", () => chartInstance2?.resize());
  } catch (error) {
    console.error("考勤数据加载失败:", error);
    message.error("考勤排名数据加载失败");
  }
};

// 内务排名
const chartRef3 = ref<HTMLElement>();
let chartInstance3: echarts.ECharts | null = null;

const initChart3 = async () => {
  try {
    const res = await http.get("/api/analysis/housekeepRank", {
      params: {
        start_time: rankDate.value[0],
        end_time: rankDate.value[1],
      },
    });

    if (res.data.code === 0) {
      //   const { topFive, bottomFive } = res.data.results;

      const { topFive, bottomFive } = res.data.results;
      const allScores = [...topFive, ...bottomFive].map((item) => item.score);

      // 计算平均分
      const average = Number(
        (
          allScores.reduce((sum, score) => sum + score, 0) / allScores.length
        ).toFixed(2)
      );

      // 处理数据格式
      const topData = topFive.map((item: any, index: number) => ({
        name: item.class_name,
        value: [index, item.score, item.inspect_date],
        itemStyle: { color: "#67C23A" }, // 绿色表示优秀
      }));

      const bottomData = bottomFive.map((item: any, index: number) => ({
        name: item.class_name,
        value: [index + topFive.length, item.score, item.inspect_date],
        itemStyle: { color: "#F56C6C" }, // 红色表示待提升
      }));

      // 配置图表
      const option = {
        title: {
          text: "内务排名分析 (平滑折线图)",
          subtext: `平均分: ${average}分`,
          left: "center",
          textStyle: {
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: (params: any) => {
            const [x, score, inspect_date] = params.data.value;
            return `
            <div style="font-weight:bold;margin-bottom:5px">${
              params.data.name
            }</div>
            <div style="margin-bottom:3px">日期: ${inspect_date}</div>
            <div style="margin-bottom:3px">考勤分: <span style="color:${
              params.color
            };font-weight:bold">${score}分</span></div>
            <div>排名: ${x < topFive.length ? "Top" : "Bottom"} ${
              x < topFive.length ? x + 1 : x - topFive.length + 1
            }</div>
          `;
          },
          backgroundColor: "rgba(255,255,255,0.9)",
          borderColor: "#ddd",
          borderWidth: 1,
          padding: [10, 15],
        },
        grid: {
          left: "12%",
          right: "12%",
          bottom: "20%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: [
            ...topFive.map((item: any) => item.class_name),
            ...bottomFive.map((item: any) => item.class_name),
          ],
          axisLabel: {
            rotate: 45,
            interval: 0,
            color: (index: number) =>
              index < topFive.length ? "#67C23A" : "#F56C6C",
            fontSize: 12,
          },
          axisLine: {
            lineStyle: {
              color: "#eee",
            },
          },
          axisTick: {
            alignWithLabel: true,
          },
        },
        yAxis: {
          type: "value",
          name: "考勤分",
          nameTextStyle: {
            padding: [0, 0, 0, 40], // 调整名称位置
          },
          min: Math.min(...allScores) - 2,
          max: Math.max(...allScores) + 2,
          axisLabel: {
            formatter: "{value} 分",
          },
          splitLine: {
            lineStyle: {
              type: "dashed",
              // color: "#f0f0f0",
            },
          },
        },
        series: [
          {
            name: "考勤排名",
            type: "line",
            smooth: true,
            symbolSize: 10,
            data: [...topData, ...bottomData],
            lineStyle: {
              width: 3,
              shadowColor: "rgba(0, 0, 0, 0.1)",
              shadowBlur: 8,
              shadowOffsetY: 5,
            },
            markLine: {
              // silent: true,
              symbol: "none",
              lineStyle: {
                color: "#409EFF",
                width: 2,
                type: "dashed",
              },
              label: {
                position: "middle",
                formatter: "平均分 {c}",
                color: "#F56C6C",
                fontSize: 12,
              },
              data: [
                {
                  yAxis: average,
                  name: "平均分",
                },
              ],
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
            },
          },
        ],
        visualMap: {
          top: 50,
          right: 20,
          pieces: [
            {
              gt: average,
              color: "#67C23A",
            },
            {
              lte: average,
              color: "#F56C6C",
            },
          ],
          textStyle: {
            color: "#666",
          },
        },
      };

      // 初始化或更新图表
      if (!chartInstance3) {
        chartInstance3 = echarts.init(chartRef3.value);
      }
      chartInstance3.setOption(option);

      // 窗口自适应
      window.addEventListener("resize", () => chartInstance3?.resize());
    }
    // chartInstance3;
  } catch (error) {
    console.error("考勤数据加载失败:", error);
    message.error("考勤排名数据加载失败");
  }
};

const chartRef4 = ref<HTMLElement>();
let chartInstance4: echarts.ECharts | null = null;
const initChart4 = async () => {
  try {
    const res = await http.get("/api/analysis/homeworkRank", {
      params: {
        start_time: rankDate.value[0],
        end_time: rankDate.value[1],
      },
    });
    if (res.data.code === 0) {
      //   const { topFive, bottomFive } = res.data.results;

      const { topFive, bottomFive } = res.data.results;
      const allScores = [...topFive, ...bottomFive].map((item) => item.score);

      // 计算平均分
      const average = Number(
        (
          allScores.reduce((sum, score) => sum + score, 0) / allScores.length
        ).toFixed(2)
      );

      // 处理数据格式
      const topData = topFive.map((item: any, index: number) => ({
        name: item.student_name,
        value: [index, item.score, item.submitted_at],
        itemStyle: { color: "#67C23A" }, // 绿色表示优秀
      }));

      const bottomData = bottomFive.map((item: any, index: number) => ({
        name: item.student_name,
        value: [index + topFive.length, item.score, item.submitted_at],
        itemStyle: { color: "#F56C6C" }, // submitted_at
      }));

      // 配置图表
      const option = {
        title: {
          text: "内务排名分析 (平滑折线图)",
          subtext: `平均分: ${average}分`,
          left: "center",
          textStyle: {
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: (params: any) => {
            const [x, score, date] = params.data.value;
            return `
            <div style="font-weight:bold;margin-bottom:5px">${
              params.data.name
            }</div>
            <div style="margin-bottom:3px">日期: ${date}</div>
            <div style="margin-bottom:3px">考勤分: <span style="color:${
              params.color
            };font-weight:bold">${score}分</span></div>
            <div>排名: ${x < topFive.length ? "Top" : "Bottom"} ${
              x < topFive.length ? x + 1 : x - topFive.length + 1
            }</div>
          `;
          },
          backgroundColor: "rgba(255,255,255,0.9)",
          borderColor: "#ddd",
          borderWidth: 1,
          padding: [10, 15],
        },
        grid: {
          left: "12%",
          right: "12%",
          bottom: "20%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: [
            ...topFive.map((item: any) => item.student_name),
            ...bottomFive.map((item: any) => item.student_name),
          ],
          axisLabel: {
            rotate: 45,
            interval: 0,
            color: (index: number) =>
              index < topFive.length ? "#67C23A" : "#F56C6C",
            fontSize: 12,
          },
          axisLine: {
            lineStyle: {
              color: "#eee",
            },
          },
          axisTick: {
            alignWithLabel: true,
          },
        },
        yAxis: {
          type: "value",
          name: "考勤分",
          nameTextStyle: {
            padding: [0, 0, 0, 40], // 调整名称位置
          },
          min: Math.min(...allScores) - 2,
          max: Math.max(...allScores) + 2,
          axisLabel: {
            formatter: "{value} 分",
          },
          splitLine: {
            lineStyle: {
              type: "dashed",
              // color: "#f0f0f0",
            },
          },
        },
        series: [
          {
            name: "考勤排名",
            type: "line",
            smooth: true,
            symbolSize: 10,
            data: [...topData, ...bottomData],
            lineStyle: {
              width: 3,
              shadowColor: "rgba(0, 0, 0, 0.1)",
              shadowBlur: 8,
              shadowOffsetY: 5,
            },
            markLine: {
              // silent: true,
              symbol: "none",
              lineStyle: {
                color: "#409EFF",
                width: 2,
                type: "dashed",
              },
              label: {
                position: "middle",
                formatter: "平均分 {c}",
                color: "#F56C6C",
                fontSize: 12,
              },
              data: [
                {
                  yAxis: average,
                  name: "平均分",
                },
              ],
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
            },
          },
        ],
        visualMap: {
          top: 50,
          right: 20,
          pieces: [
            {
              gt: average,
              color: "#67C23A",
            },
            {
              lte: average,
              color: "#F56C6C",
            },
          ],
          textStyle: {
            color: "#666",
          },
        },
      };

      // 初始化或更新图表
      if (!chartInstance4) {
        chartInstance4 = echarts.init(chartRef4.value);
      }
      chartInstance4.setOption(option);

      // 窗口自适应
      window.addEventListener("resize", () => chartInstance4?.resize());
    }
  } catch (error) {
    console.error("考勤数据加载失败:", error);
    message.error("考勤排名数据加载失败");
  }
};
const height = ref<string>("350px");

// 初始化加载
onMounted(() => {
  initChart1();
  initChart2();
  initChart3();
  initChart4();
});
</script>
  
  <style scoped>
.rank-charts {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 20px;
}

/* 统一图表卡片样式 */
:deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
</style>